package routers

import (
	. "gddgame.cc/galaxy/common/dsl/web"
	app "gddgame.cc/galaxy/core/controllers/app"
	user "gddgame.cc/galaxy/core/controllers/user"
	"gddgame.cc/galaxy/core/models"
	"gddgame.cc/galaxy/core/sdk"
	"gddgame.cc/galaxy/utils/def"

	"gddgame.cc/galaxy/server/composer"
	"gddgame.cc/galaxy/server/web"
	"gddgame.cc/galaxy/server/web/middleware"
)

func UserToken(context web.Context) bool {
	token := context.Header("token")
	if token == "" {
		return false
	}
	var app models.App
	if err := context.Get("app", &app); err != nil {
		return false
	}
	result, err := user.ValidToken(context, &app, token)
	if err != nil {
		return false
	}
	if err := context.Set("open_id", result.Id); err != nil {
		return false
	}
	return true
}
func AppRelation(context middleware.Context, next middleware.Next) error {
	appId := context.Header("appId")
	appToken := context.Header("appToken")
	if appId != "" {
		result, err := app.ValidToken(context, appId, appToken)
		if err == nil {
			if err := context.Set("app", result); err != nil {
				return err
			}
		}
		if err := next(nil); err != nil {
			return err
		}
		if err == nil {
			if err := context.Set("app", nil); err != nil {
				return err
			}
		}
		return err
	} else {
		return next(nil)
	}
}

//* 用户信息
func ProjectUserHandler(path string, builder composer.Builder, router web.Router, client *sdk.AppClient) error {
	if err := user.InitUser(builder, builder); err != nil {
		return err
	}
	r := NewSwaggerRouter(path, builder, router, &SwaggerRouterConfig{
		Info: SwaggerInfo{
			Title: "",
		},
	})
	web.Restful(router)
	auth := SessionAuthHandler(builder, builder.Cache("user"), r.Router, "id", "Id")
	r.Security().OnFail(DefaultAuthFail)
	r.Security().Key("session", CookieLocation, SessionAuth, true)
	r.Security().Key("token", HeaderLocation, UserToken, true)
	//r.Use(AppRelation)

	router.Post("/auth/login", Controller([]Param{
		{Name: "app", Default: client.App()},
		{Name: "username", In: Body},
		{Name: "password", In: Body},
	}, user.Login, auth.Login))
	router.Post("/auth/logout", Controller([]Param{}, auth.Logout))

	r.Get("/share", Swagger{
		Controller: func(context def.Context) {

		},
		Response: ApiResponse,
	})
	return nil
}
